package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.SchoolService;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger; // 使用 SLF4J 的 Logger
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

@WebServlet("/schoolCreate.ctl")
public class SchoolCreateCtrl extends HttpServlet {
    // 正确使用 SLF4J 的 Logger
    private static final Logger log = LoggerFactory.getLogger(SchoolCreateCtrl.class);

    // 获取 schoolService 对象
    private SchoolService schoolService = ServiceFactory.getService(SchoolService.class, "SchoolServiceImpl");

    // 构造器声明异常
    public SchoolCreateCtrl() throws BaseException, InvocationTargetException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        // 根据 request 对象，获得代表参数的 JSON 字串
        String school_json = JSONUtil.getJSON(request);
        // 将 JSON 字串解析为 School 对象
        School schoolToAdd = JSON.parseObject(school_json, School.class);
        // 设置响应字符编码为 UTF-8
        response.setContentType("application/json;charset=UTF-8");
        // 创建 JSON 对象 message, 以便往前端响应信息
        JSONObject message = new JSONObject();
        // 在数据库表中增加 School 对象
        try {
            schoolService.add(schoolToAdd); // 调用正确的 service 方法
            message.put("msg", "增加成功");
            message.put("code", "200");
            log.info("学校创建成功！");
        } catch (SQLException e) {
            message.put("msg", "数据库操作异常");
            message.put("code", "500"); // 错误状态码应为 500
            // 记录 SQLException 的错误信息
            log.error("数据库操作异常: {}", e.getMessage(), e);
        } catch (Exception e) {
            message.put("msg", "网络异常");
            message.put("code", "500"); // 错误状态码应为 500
            // 记录其它的错误信息
            log.error("网络异常: {}", e.getMessage(), e);
        }
        // 响应 message 到前端
        response.getWriter().println(JSON.toJSONString(message));
    }
}
